#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time : 2025/7/15 22:26
# @Author : liuqi
# @File : views.py
# @Software: PyCharm
# @Describe:
import json
import re
from datetime import datetime

from flask import request, make_response, jsonify, session
import logging
import random
from ... import constants, db
from . import pass_blue
from info.utils.captcha.captcha import captcha
from ... import redis_store
from ...constants import IMAGE_CODE_REDIS_EXPIRES
from info.utils.yuntongxun.sms import CCP
from ...models import User
from ...utils.response_code import RET




@pass_blue.route('/logout', methods=['POST'])
def logout():
    session.pop('user_id', None)
    return jsonify(errno=RET.OK,errmsg='退出成功')

# 请求路径:/passport/image_code
# 请求方式:get
# 请求参数: cur_id,pre_id
# 返回值:图片验证码
# 功能:获取图片验证码
@pass_blue.route('/image_code')
def image_code():
    cur_id = request.args.get("cur_id")
    pre_id = request.args.get("pre_id")
    name, text, image_data = captcha.generate_captcha()
    # 将图片验证码的值保存
    try:
        redis_store.set('image_code:%s' % cur_id, text, IMAGE_CODE_REDIS_EXPIRES)
        # 判断是否有上一次的图片验证码
        if pre_id:
            redis_store.delete('image_code:%s' % pre_id)
    except Exception as e:
        logging.error(e)
        return '图片验证码操作失败'
    response = make_response(image_data)
    response.headers['Content-Type'] = 'image/jpg'
    return response


@pass_blue.route('/sms_code',methods=['POST'])
def sms_send_code():
    # 1.获取参数
    json_data = request.data
    dict_data = json.loads(json_data)
    mobile = dict_data.get('mobile')
    image_code = dict_data.get("image_code")
    image_code_id = dict_data.get("image_code_id")
    # 2.参数为空校验
    if not all([mobile, image_code, image_code_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不全")
    # 3,验证手机号格式
    if not re.match("1[3-9]\d{9}", mobile):
        return jsonify(errrno=RET.DATAERR, errmsg="手机号码格式错误")
    try:
        redis_image_code = redis_store.get('image_code:%s' % image_code_id)
    except Exception as e:
        logging.error(e)
        return jsonify(errno=RET.DBERR,errmsg='操作redis失败')
    # 4.判断图片验证码是否过期
    if not redis_image_code:
        return jsonify(errno=RET.NODATA,errmsg = '图片验证码过期')
    # 判断图片验证码是否正确
    if redis_image_code.upper() != image_code.upper():
        return jsonify(errno=RET.DATAERR,errmsg='图片验证码填写有误')
    # 删除redis中的图片验证码
    try:
        redis_store.delete('image_code:%s' % image_code_id)
    except Exception as e:
        logging.error(e)
        return jsonify(errno=RET.DATAERR,errmsg='删除redis图片验证码')
    # 发送短信,调用封装好的cpp
    # cpp = CCP()
    sms_coded = "%04d"%random.randint(0, 9999)
    print(sms_coded)
    # result = cpp.send_template_sms(mobile, [sms_coded,constants.SMS_CODE_REDIS_EXPIRES/60], 1)

    # if result == -1:
    #     return jsonify(RET.DATAERR, errmsg='短信发送失败')
    # 将短信验证码保存到redis
    try:
        redis_store.set("sms_code:%s"%mobile,sms_coded,constants.SMS_CODE_REDIS_EXPIRES)
    except Exception as e:
        logging.error(e)
        return jsonify(errno=RET.DBERR,errmsg = '短信验证码保存到redis失败')
    # 返回响应
    return jsonify(error = RET.OK,errmsg = '短信发送成功')

@pass_blue.route('/register', methods=['POST'])
def register():
    # 1.获取参数
    json_data = request.data
    dict_data = json.loads(json_data)
    mobile = dict_data.get('mobile')
    sms_code = dict_data.get('sms_code')
    password = dict_data.get('password')
    # 2.检验参数为空校验
    if not all([mobile, sms_code, password]):
        return jsonify(errno =RET.PARAMERR,errmsg= '参数不全')
    # 3.手机号作为key,取出redis中的短信验证码
    try:
        redis_sms_code = redis_store.get('sms_code:%s'%mobile)
    except Exception as e:
        logging.error(e)
        return jsonify(errno =RET.DBERR,errmsg= "短信验证码取出失败")
    # 4.判断验证码是否过期
    if not redis_sms_code:
        return jsonify(errno =RET.NODATA,errmsg= '短信验证码已经过期')
    # 5.判断短信验证码是否正确
    if redis_sms_code != sms_code:
        return jsonify(errno =RET.DATAERR,errmsg='短信验证码错误')
    # 6.删除短信验证码
    try:
        redis_store.delete('sms_code:%s'%mobile)
    except Exception as e:
        logging.error(e)
        return jsonify(errno =RET.DBERR,errmsg= "短信验证码删除失败")
    user = User()
    user.nick_name = mobile
    user.password = password
    user.mobile = mobile
    user.signature = '该用户很懒,什么都没写'
    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        logging.error(e)
        return jsonify(errno =RET.DATAERR,errmsg = '用户注册失败')
    return jsonify(errno = RET.OK,errmsg = '注册成功')

@pass_blue.route('/login', methods=['POST'])
def login():
    """
    1. 获取参数
    2. 校验参数,为空校验
    3. 通过用户手机号,到数据库查询用户对象
    4. 判断用户是否存在
    5. 校验密码是否正确
    6. 将用户的登陆信息保存在session中
    7. 返回响应
    :return:
    """
    # 获取参数
    dict_data = request.json
    mobile = dict_data.get('mobile')
    password = dict_data.get('password')
    if not all([mobile, password]):
        return jsonify(errno=RET.PARAMERR,errnsg='参数不全')
    try:
        user = User.query.filter_by(mobile=mobile).first()
    except Exception as e:
        logging.error(e)
    if not user:
        return jsonify(errno=RET.DBERR,errmsg='用户不存在')
    if not user.check_passowrd(password):
        return jsonify(errno=RET.DATAERR,errmsg='密码错误')
    # 6.将用户的登陆信息保存在session中
    session['user_id'] = user.id
    # 7,记录用户最后的登录时间
    user.last_login = datetime.now()
    db.session.commit()
    return jsonify(errno=RET.OK, errmsg="登陆成功")